package dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import utils.DbUtil;

import dao.RoleDao;
import entity.Role;

public class RoleDaoImpl implements RoleDao {

	public List<Role> getList(int offset, int limit, String condition, String order) throws SQLException {
		StringBuffer sb = new StringBuffer();
		sb.append("select * from j_role");
		if(!"".equals(condition)) {
			sb.append(" where "+condition+" ");
		}
		sb.append(order);
		sb.append(" limit "+offset+", "+limit);
		System.out.println("sql="+sb.toString());
		return DbUtil.queryRunner().query(sb.toString(), new BeanListHandler<Role>(Role.class));
	}

	public int getListCount(String condition) throws SQLException {
		StringBuffer sb = new StringBuffer();
		sb.append("select count(*) from j_role");
		if(!"".equals(condition)) {
			sb.append(" where "+condition+" ");
		}
		Long count = DbUtil.queryRunner().query(sb.toString(), new ScalarHandler<Long>());
		return count.intValue();
	}

	@SuppressWarnings("deprecation")
	public Role getRoleById(String roleId) throws SQLException {
		return DbUtil.queryRunner().query("select * from j_role where id=?", roleId, new BeanHandler<Role>(Role.class));
	}

	public List<Role> getRoleList() throws SQLException {
		return DbUtil.queryRunner().query("select * from j_role", new BeanListHandler<Role>(Role.class));
	}

	public int addRole(Role role) throws SQLException {
		Object[] params = {role.getName(),role.getAuth(),role.getDate_entered(),role.getUpdate_entered()};
		return DbUtil.queryRunner().update("insert into j_role (name,auth,date_entered,update_entered) values (?,?,?,?)", params);
	}

	public int deleteRoleById(String id) throws SQLException {
		return DbUtil.queryRunner().update("delete from j_role where id in(?)",	id);
	}

	public int editRole(Role role) throws SQLException {
		Object[] params = {role.getName(),role.getAuth(),role.getUpdate_entered(),role.getId()};
		return DbUtil.queryRunner().update("update j_role set name=?,auth=?,update_entered=? where id=?", params);
	}
	
}
